import Taro from '@tarojs/taro'
import { concatWithTalentUrl } from './ServerUrls'

/**
 * HTTP 请求
 * @param options
 * @param refresh
 */
let isLoading = false
export default function request(options: Taro.request.Option, refresh = false): Promise<any> {

  if (!isLoading) {
    isLoading = true
    Taro.showLoading({ title: '加载中...', mask: true })
  }
  return new Promise(async (resolve, reject) => {
    // 请求成功后的回调
    options.success = (res) => {
      if (isLoading) {
        isLoading = false
        Taro.hideLoading()
      }

      // console.log("HTTP-RE", res)
      const { data, statusCode } = res
      if (statusCode === 200) {
        resolve(data)
      } else {
        if (statusCode === 401) {
          const user_name = Taro.getStorageSync('userNames')
          Taro.setStorageSync('userNames', user_name)
          Taro.reLaunch({ url: '/pages/login/index' })
          Taro.showToast({ title: '会话超时', icon: 'none' })
        }
        reject(data)
      }
    }
    // 请求失败后的回调
    options.fail = (res) => {
      if (isLoading) {
        isLoading = false
        Taro.hideLoading()
      }
      reject(res)
    }
    options.url = concatWithTalentUrl(options.url)
    Taro.request(options)
  })
}

/**
 * OPTIONS 请求
 * @param url
 * @param options
 */
export function OPTIONS(url: string, options?: object) {
  return request({ url, method: 'OPTIONS', ...options })
}

/**
 * GET 请求
 * @param url
 * @param params
 * @param options
 */
export function GET(url: string, params?: any, options?: object) {
  return request({ url, method: 'GET', data: params, ...options })
}

/**
 * POST 请求
 * @param url
 * @param data
 * @param options
 */
export function POST(url: string, data?: any, options?: object) {
  return request({ url, method: 'POST', data, ...options })
}

/**
 * PUT 请求
 * @param url
 * @param data
 * @param options
 */
export function PUT(url: string, data?: any, options?: object) {
  return request({ url, method: 'PUT', data, ...options })
}

/**
 * DELETE 请求
 * @param url
 * @param params
 * @param options
 */
export function DELETE(url: string, params?: any, options?: object) {
  return request({ url, method: 'DELETE', data: params, ...options })
}

/**
 * DELETE 请求
 * @param url
 * @param data
 * @param options
 */
export function TRACE(url: string, data?: any, options?: object) {
  return request({ url, method: 'TRACE', data, ...options })
}
